package org.southyin.securitysamples.config;

import org.southyin.securitysamples.model.Menu;
import org.southyin.securitysamples.model.Role;
import org.southyin.securitysamples.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import java.util.Collection;
import java.util.List;

/**
 * 根据 访问接口 返回 角色信息
 */
@Component
public class MyFilterDatasource implements FilterInvocationSecurityMetadataSource {
    @Autowired
    MenuService service;
    AntPathMatcher matcher = new AntPathMatcher();
    @Override
    public Collection<ConfigAttribute> getAttributes(Object o) throws IllegalArgumentException {
        // 获取请求接口
        String requestUrl = ((FilterInvocation) o).getRequestUrl();
        // 查询所有 接口 和 角色 的对应关系
        List<Menu> menus = service.getMenuRoles();
        // 遍历 menus 找到 requestUrl 需要的角色
        for (Menu menu : menus) {
            if (matcher.match(menu.getPattern(), requestUrl)) {
                List<Role> roles = menu.getRoles();
                String[] arr = new String[roles.size()];
                int index = 0;
                for (Role role : roles) {
                    arr[index] = role.getRname();
                    index++;
                }
                return SecurityConfig.createList(arr);
            }
        }
        return SecurityConfig.createList("ROLE_login");
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
}
